<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue';
import * as echarts from 'echarts/core';
import { LineChart } from 'echarts/charts';
import { GridComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { useMeterStore } from '@/stores/meter';
import { useReportStore } from '@/stores/report';
import dayjs from 'dayjs';

echarts.use([LineChart, GridComponent, CanvasRenderer]);

const chartRefs = ref([]);

const props = defineProps({
    loading: {
        type: Boolean,
        default: false
    }
});

const reportStore = useReportStore();
const meterStore = useMeterStore();

// 简化的数字格式化
const formatNumber = (value) => {
    if (!value && value !== 0) return '0';
    return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

const getTypeInfo = computed(() => {
    const typeMap = {
        1: { unit: 'm³', name: '用水量' },
        2: { unit: 'kWh', name: '用电量' },
        3: { unit: 'm³', name: '用气量' }
    };
    return typeMap[meterStore.currentSelectedType] || { unit: '', name: '使用量' };
});

const displayStats = computed(() => {
    if (props.loading || reportStore.isLoading || !reportStore.companyReportData) {
        return Array(3).fill({
            title: '',
            total: 0,
            timeRange: '',
            data: new Array(24).fill(0)
        });
    }

    const { half_hour = {}, day = {}, month = {}, year = {} } = reportStore.companyReportData || {};
    return [
        {
            title: `昨日${getTypeInfo.value.name}总量`,
            total: day && day.data && day.data.length > 0 ? day.data.slice(-1)[0].value : 0,
            timeRange: dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
            data: half_hour?.data?.map(item => item.value) || new Array(24).fill(0)
        },
        {
            title: `本月${getTypeInfo.value.name}总量`,
            total: month && month.data && month.data.length > 0 ? month.data.slice(-1)[0].value : 0,
            timeRange: dayjs().format('YYYY-MM'),
            data: day?.data?.map(item => item.value) || new Array(31).fill(0)
        },
        {
            title: `本年${getTypeInfo.value.name}总量`,
            total: year && year.data && year.data.length > 0 ? year.data.slice(-1)[0].value : 0,
            timeRange: dayjs().format('YYYY'),
            data: month?.data?.map(item => item.value) || new Array(12).fill(0)
        }
    ];
});

// 图表配置
const createChartOption = (data = []) => ({
    animation: false,
    grid: {
        top: 5,
        right: 5,
        bottom: 5,
        left: 5,
        containLabel: false
    },
    xAxis: {
        type: 'category',
        show: false,
        boundaryGap: false
    },
    yAxis: {
        type: 'value',
        show: false,
        scale: true
    },
    series: [{
        type: 'line',
        data: data,
        smooth: true,
        symbol: 'none',
        lineStyle: {
            width: 2,
            color: '#409EFF'
        },
        areaStyle: {
            color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                    offset: 0,
                    color: 'rgba(64, 158, 255, 0.3)'
                }, {
                    offset: 1,
                    color: 'rgba(64, 158, 255, 0.1)'
                }]
            }
        }
    }]
});

let chartInstances = [];

const initCharts = async () => {
    if (props.loading) return;

    // 清理旧的图表实例
    chartInstances.forEach(chart => chart?.dispose());
    chartInstances = [];

    await nextTick();

    // 初始化新的图表实例
    chartRefs.value.forEach((el, index) => {
        if (el && displayStats.value[index]) {
            const chart = echarts.init(el);
            chart.setOption(createChartOption(displayStats.value[index].data));
            chartInstances.push(chart);
        }
    });
};

// 处理窗口大小变化
const handleResize = () => {
    chartInstances.forEach(chart => chart?.resize());
};

let updateTimer = null;
const debouncedUpdateCharts = () => {
    if (updateTimer) clearTimeout(updateTimer);
    updateTimer = setTimeout(async () => {
        await initCharts();
    }, 300);
};

// 监听数据变化
watch(
    [displayStats, () => meterStore.currentSelectedType],
    debouncedUpdateCharts,
    { deep: true }
);

onMounted(() => {
    window.addEventListener('resize', handleResize);
    debouncedUpdateCharts();
});

onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize);
    if (updateTimer) clearTimeout(updateTimer);
    chartInstances.forEach(chart => chart?.dispose());
    chartInstances = [];
});
</script>

<template>
    <div class="stats-scroll-container">
        <el-row :gutter="16" class="energy-stats">
            <!-- 使用响应式栅格：桌面端每行3个，平板端每行2个，手机端每行1个 -->
            <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8" v-for="(stat, index) in displayStats" :key="index"
                class="stat-col">
                <el-card class="stat-card">
                    <div class="card-content">
                        <!-- 加载中状态 -->
                        <template v-if="loading">
                            <div class="stat-info">
                                <el-skeleton animated :rows="2">
                                    <template #template>
                                        <el-skeleton-item variant="h3" style="width: 80%; margin-bottom: 12px" />
                                        <el-skeleton-item variant="p" style="width: 70%; margin: 12px 0" />
                                    </template>
                                </el-skeleton>
                            </div>
                            <div class="mini-chart-skeleton">
                                <el-skeleton animated>
                                    <template #template>
                                        <el-skeleton-item variant="image" style="width: 100%; height: 80px" />
                                    </template>
                                </el-skeleton>
                            </div>
                        </template>

                        <!-- 实际内容 -->
                        <template v-else>
                            <div class="stat-info">
                                <h3 class="stat-title" :title="stat.title">{{ stat.title }}</h3>
                                <p class="stat-value">
                                    <AnimatedNumber :suffix="getTypeInfo.unit" :value="stat.total"
                                        :formatter="formatNumber" />
                                </p>
                                <p class="stat-time">{{ stat.timeRange }}</p>
                            </div>
                            <div class="mini-chart" ref="chartRefs"></div>
                        </template>
                    </div>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<style scoped>
.stats-scroll-container {
    width: 100%;
    padding-top: var(--gap-normal);
}

.energy-stats {
    width: 100%;
    height: 100%;
}

.stat-col {
    margin-bottom: 16px;
}

.stat-card {
    height: 100%;
}

.card-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    min-height: 120px;
}

.stat-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    margin-right: 1rem;
    min-width: 0;
    /* 防止flex子元素溢出 */
}

.mini-chart {
    width: 50%;
    height: 100px;
    min-width: 100px;
    flex-shrink: 0;
}

.stat-title {
    margin: 0;
    font-size: 0.875rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: 1.4;
}

.stat-value {
    font-size: 1.25rem;
    font-weight: bold;
    margin: 0.5rem 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: 1.2;
}

.stat-time {
    font-size: 0.75rem;
    color: var(--el-text-color-secondary);
    margin: 0.25rem 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: 1.3;
}

.mini-chart-skeleton {
    width: 50%;
    height: 100px;
    flex-shrink: 0;
}

/* 平板端适配 */
@media screen and (max-width: 1400px) {
    .card-content {
        min-height: 110px;
    }

    .stat-title {
        font-size: 0.8rem;
    }

    .stat-value {
        font-size: 1.1rem;
    }

    .mini-chart {
        width: 45%;
        height: 90px;
        min-width: 90px;
    }
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
    .stats-scroll-container {
        padding-bottom: 1rem;
    }

    .energy-stats {
        margin: 0 -8px;
    }

    .stat-col {
        padding: 0 8px !important;
        margin-bottom: 12px;
    }

    .card-content {
        flex-direction: column;
        align-items: stretch;
        min-height: auto;
        padding: 0;
    }

    .stat-info {
        margin-right: 0;
        margin-bottom: 1rem;
        text-align: center;
    }

    .stat-title {
        font-size: 0.9rem;
        margin-bottom: 0.5rem;
    }

    .stat-value {
        font-size: 1.5rem;
        margin: 0.3rem 0;
    }

    .stat-time {
        font-size: 0.8rem;
        margin-top: 0.3rem;
    }

    .mini-chart {
        width: 100%;
        height: 80px;
        min-width: auto;
    }

    .mini-chart-skeleton {
        width: 100%;
        height: 80px;
    }
}
</style>